package com.agent.platform.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.agent.platform.dto.TaskCallbackDTO;
import com.agent.platform.dto.TaskCreateDTO;
import com.agent.platform.entity.AgentInfo;
import com.agent.platform.entity.TaskInfo;
import com.agent.platform.exception.BusinessException;
import com.agent.platform.mapper.AgentInfoMapper;
import com.agent.platform.mapper.TaskInfoMapper;
import com.agent.platform.mq.TaskMessage;
import com.agent.platform.mq.TaskProducer;
import com.agent.platform.vo.TaskVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class TaskService {
    
    private final TaskInfoMapper taskInfoMapper;
    private final AgentInfoMapper agentInfoMapper;
    private final TaskProducer taskProducer;
    
    public TaskVO create(TaskCreateDTO dto) {
        String taskId = "task_" + IdUtil.fastSimpleUUID();
        
        TaskInfo task = new TaskInfo();
        BeanUtil.copyProperties(dto, task);
        task.setTaskId(taskId);
        task.setStatus("PENDING");
        
        taskInfoMapper.insert(task);
        
        // 发送任务到消息队列
        TaskMessage message = new TaskMessage(taskId, task.getTaskType(), 0);
        taskProducer.sendTask(message);
        
        log.info("任务已创建并发送到队列: taskId={}", taskId);
        
        return BeanUtil.copyProperties(task, TaskVO.class);
    }
    

    
    public void callback(TaskCallbackDTO dto) {
        TaskInfo task = getByTaskId(dto.getTaskId());
        
        task.setStatus(dto.getStatus());
        task.setOutputData(dto.getOutputData());
        task.setErrorMessage(dto.getErrorMessage());
        
        if ("SUCCESS".equals(dto.getStatus()) || "FAILED".equals(dto.getStatus())) {
            task.setEndTime(LocalDateTime.now());
        }
        
        taskInfoMapper.updateById(task);
    }
    
    public Page<TaskVO> list(Integer current, Integer size, String taskType, String status) {
        Page<TaskInfo> page = new Page<>(current, size);
        LambdaQueryWrapper<TaskInfo> wrapper = new LambdaQueryWrapper<>();
        
        if (taskType != null && !taskType.isEmpty()) {
            wrapper.eq(TaskInfo::getTaskType, taskType);
        }
        if (status != null && !status.isEmpty()) {
            wrapper.eq(TaskInfo::getStatus, status);
        }
        wrapper.orderByDesc(TaskInfo::getCreateTime);
        
        Page<TaskInfo> result = taskInfoMapper.selectPage(page, wrapper);
        Page<TaskVO> voPage = new Page<>(result.getCurrent(), result.getSize(), result.getTotal());
        voPage.setRecords(result.getRecords().stream()
            .map(task -> BeanUtil.copyProperties(task, TaskVO.class))
            .toList());
        return voPage;
    }
    
    public TaskVO getDetail(String taskId) {
        TaskInfo task = getByTaskId(taskId);
        return BeanUtil.copyProperties(task, TaskVO.class);
    }
    
    public void retryPendingTasks() {
        LambdaQueryWrapper<TaskInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskInfo::getStatus, "PENDING");
        
        List<TaskInfo> tasks = taskInfoMapper.selectList(wrapper);
        for (TaskInfo task : tasks) {
            TaskMessage message = new TaskMessage(task.getTaskId(), task.getTaskType(), 0);
            taskProducer.sendTask(message);
        }
        log.info("重新发送 {} 个待处理任务到队列", tasks.size());
    }
    
    private TaskInfo getByTaskId(String taskId) {
        LambdaQueryWrapper<TaskInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskInfo::getTaskId, taskId);
        TaskInfo task = taskInfoMapper.selectOne(wrapper);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }
        return task;
    }
}
